package org.upt.dcda;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.upt.dcda.db.TagEntity;
import org.upt.dcda.exceptions.BookstoreException;
import org.upt.dcda.exceptions.TagNotFoundException;

/**
 * Session Bean implementation class TagManagerBean
 */
@Stateless
@LocalBean
public class TagManagerBean implements TagManagerBeanRemote,
		TagManagerBeanLocal
{

	@PersistenceContext
	private EntityManager	entityManager;

	/**
	 * Default constructor.
	 */
	public TagManagerBean()
	{
		// TODO Auto-generated constructor stub
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public void addTag(String tagName) throws BookstoreException
	{
		try
		{
			TagEntity tag = new TagEntity();

			tag.setTagName(tagName);

			entityManager.persist(tag);
		}
		catch (Throwable t)
		{
			throw new BookstoreException("Caught exception: " + t.toString(), t);
		}

	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public List<TagEntity> getAllTags() throws BookstoreException
	{
		try
		{

			Query query = entityManager
					.createNamedQuery(TagEntity.VIEW_ALL_TAGS);

			List<TagEntity> resultList = (List<TagEntity>) query
					.getResultList();
			return resultList;

		}
		catch (Throwable t)
		{
			throw new BookstoreException("Caught exception: " + t.toString(), t);
		}
	}

	@Override
	public TagEntity getTagById(int tagId) throws BookstoreException
	{
		TagEntity tag = entityManager.find(TagEntity.class, tagId);
		if (tag == null)
			throw new TagNotFoundException();

		return tag;
	}

}
